// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
	_before: function() { // 通用预处理器

	},
	/**
	 * method1方法描述
	 * @param {string} data 参数1描述
	 * @returns {object} 返回值描述
	 */
	async sendMessage() {
	
		// 获取url参数
		const httpInfo = this.getHttpInfo()
		const data = JSON.parse(httpInfo.body)
		// 参数校验，如无参数则不需要
		if (!data) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		// 获取token
		const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/cgi-bin/token', {
			method: 'get',
			data: {
				grant_type: 'client_credential',
				appid: 'wx43075af6660fe782',
				secret: '968073e75c30b67f806db8b6be95ff11'
			},
			dataType: 'json'

		})
		const token = res.data.access_token
		// 发送订阅消息
		const resMessage = await uniCloud.httpclient.request(
			'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + token, {
				method: 'POST',
				data: {
					touser:data.toUser,
					page:data.page,
					template_id: 'rAG8ViGLQH99zGxJASwSpTC4zd7OQg0_kk4zNacOUeI',
					data: data.data,
					miniprogram_state: "developer",
					lang: "zh_CN"
				},
				dataType: 'json',
				contentType: 'json'

			})

		// 返回结果
		return {
			data: resMessage.data
		}
	}
}